<template>
  <div class="container">
    <van-popup round v-model="popupShow" position="bottom">
      <template v-if="popupState == 'cascader'">
        <van-cascader
          :field-names="fieldNames"
          v-model="cascaderValue"
          title="请选择所属区域"
          :options="cascadeOptions"
          active-color="#D58913"
          @finish="cascaderFinish"
          @close="cascaderClose"
        />
      </template>
    </van-popup>
    <h1 style="text-align: center" v-if="!formData.card_no">
      请使用"e大连"扫描二维码
    </h1>
    <div class="container-inner" v-if="formData.card_no">
      <van-form
        ref="form"
        scroll-to-error
        :show-error-message="false"
        @failed="onFailed"
        @submit="onSubmit"
      >
        <div class="card">
          <div class="card-bar">
            <div class="card-bar-title">外来人员注册</div>
          </div>
          <div class="card-container">
            <van-field
              v-model="formData.name"
              required
              clearable
              readonly
              maxlength="20"
              :rules="[{ required: true, message: '请检查姓名' }]"
              name="name"
              label="姓名"
              placeholder="请输入姓名"
            >
            </van-field>
            <van-field
              v-model="formData.tel"
              required
              clearable
              readonly
              maxlength="11"
              type="tel"
              :rules="[{ required: true, message: '请检查联系方式' }]"
              name="tel"
              label="联系方式"
              placeholder="请输入联系方式"
            >
            </van-field>
            <van-field
              v-model="formData.card_no"
              required
              clearable
              readonly
              maxlength="18"
              :rules="[
                {
                  required: true,
                  validator: cardNoValidator,
                  message: '请检查身份证号',
                },
              ]"
              name="card_no"
              label="身份证号"
              placeholder="请输入身份证号"
              @blur="cardNoChange"
            >
            </van-field>
            <van-field
              name="sex"
              required
              :rules="[{ required: true, message: '请检查性别' }]"
              label="性别"
            >
              <template #input>
                <van-radio-group
                  v-model="formData.sex"
                  checked-color="#D58913"
                  direction="horizontal"
                >
                  <van-radio name="1">男</van-radio>
                  <van-radio name="2">女</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <van-field
              readonly
              clickable
              is-link
              name="ascription"
              :value="formData.ascription"
              label="所属区域"
              placeholder="点击选择"
              @click="pickerChange('ascription')"
              required
              :rules="[{ required: true, message: '请检查所属区域' }]"
            >
            </van-field>
            <van-field
              v-model="formData.quarter"
              required
              clearable
              maxlength="20"
              :rules="[{ required: true, message: '请检查所属小区' }]"
              name="quarter"
              placeholder="请输入所属小区"
            >
              <template #label>
                <div class="field-title">所属小区</div>
                <div class="field-text">(或无则住宅楼名)</div>
              </template>
            </van-field>
            <van-field
              v-model="formData.address"
              rows="3"
              autosize
              label="详细地址"
              type="textarea"
              maxlength="255"
              placeholder="请输入详细地址"
              required
              :rules="[{ required: true, message: '请检查详细地址' }]"
            >
            </van-field>
          </div>
        </div>
      </van-form>
    </div>

    <div class="bottom-bar" v-if="formData.card_no">
      <van-button
        class="bottom-bar-btn"
        block
        size="large"
        color="#D58913"
        type="info"
        text="确认提交"
        @click="submitAction"
      />
    </div>
  </div>
</template>

<script>
import { getSexByIdCard, identityCodeValid } from '@/libs/tools'
import { getDLAreaList, insertVisitPeople } from '@/api/school.js'

export default {
  name: 'Register',

  data() {
    return {
      popupShow: false,
      popupState: '',
      formData: {},
      cascaderShow: false,
      cascaderValue: '',
      cascadeOptions: [],
      fieldNames: {
        text: 'name',
        value: 'code',
        children: 'children',
      },
    }
  },

  computed: {},

  watch: {},

  mounted() {
    this.formData.card_no = this.$route.query.card_no
    this.formData.name = this.$route.query.name
    this.formData.tel = this.$route.query.mobile
    if (this.formData.card_no) {
      this.cardNoChange()
      this.getDLAreaList()
    }
  },

  methods: {
    async getDLAreaList() {
      const areaData = await getDLAreaList()
      if (areaData.data.errcode == 0) {
        let options = this.$common.xeUtils.toArrayTree(areaData.data.data, {
          strict: true,
          parentKey: 'parent_id',
          key: 'id',
          children: 'children',
        })
        this.cascadeOptions = options[0].children
      }
    },
    cardNoChange() {
      let sex = getSexByIdCard(this.formData.card_no)
      if (sex) this.$set(this.formData, 'sex', sex.code)
    },
    pickerChange(type) {
      switch (type) {
        case 'ascription':
          this.popupState = 'cascader'
          this.popupShow = true
          break
      }
    },
    cascaderFinish({ value, selectedOptions, tabIndex }) {
      this.formData.ascription =
        selectedOptions[0].name +
        '/' +
        selectedOptions[1].name +
        '/' +
        selectedOptions[2].name
      this.formData.area_code = selectedOptions[0].code
      this.formData.street_code = selectedOptions[1].code
      this.formData.community_code = selectedOptions[2].code
      this.formData.area_name = selectedOptions[0].name
      this.formData.street_name = selectedOptions[1].name
      this.formData.community_name = selectedOptions[2].name
      this.popupShow = false
    },
    cascaderClose() {
      this.formData.ascription = ''
      this.formData.area_code = ''
      this.formData.street_code = ''
      this.formData.community_code = ''
      this.formData.area_name = ''
      this.formData.street_name = ''
      this.formData.community_name = ''
      this.popupShow = false
    },
    failNotice(msg) {
      this.$notify({ type: 'danger', message: msg })
    },
    onFailed(errorInfo) {
      this.failNotice(errorInfo.errors[0].message)
    },
    // 身份证校验
    cardNoValidator(val) {
      const reg = identityCodeValid(val)
      if (!reg.pass) return false
    },
    submitAction() {
      this.$refs.form.submit()
    },
    async onSubmit() {
      this.$dialog
        .confirm({
          title: '是否确认提交',
          message: '',
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          confirmButtonColor: '#D58913',
          beforeClose: async (action, done) => {
            if (action === 'confirm') {
              const param = { ...this.formData }
              console.log('最终提交信息', param)
              const insertData = await insertVisitPeople(param)
              if (insertData.data.errcode == 0) {
                this.$toast('操作成功')
                this.$emit('changeRegister')
                done()
              } else {
                this.$toast(insertData.data.errmsg)
                done()
              }
            } else {
              done()
            }
          },
        })
        .catch(() => {})
    },
  },
}
</script>

<style lang="less" scoped>
.container /deep/ .van-checkbox {
  min-height: 30px;
}

.container /deep/ .van-field__label span {
  display: inline-block;
  padding-left: 5px;
  width: 90%;
  text-align-last: justify;
}

.container {
  background: #f2f7fb;
  width: 100%;
  height: 100vh;
  box-sizing: border-box;

  &-inner {
    padding: 20px;
    .card {
      background: inherit;

      &-container {
        border-radius: 10px;
        overflow: hidden;
        background-color: white;
        padding: 10px;
      }
    }
  }

  .bottom-bar {
    position: absolute;
    bottom: 0;
    width: 100%;
    &-btn {
    }
  }
}
</style>
